package sys_users

import (
	"context"
	"log"
	"time"
	"wave-service/server/app/common/jwtx"
	"wave-service/server/app/common/response"
	"wave-service/server/app/validate"

	"wave-service/server/app/internal/svc"
	"wave-service/server/app/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SysUserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSysUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SysUserLoginLogic {
	return &SysUserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SysUserLoginLogic) SysUserLogin(req *types.SysUserLoginRequest) (resp *types.SysUserLoginResponse, err error) {
	errStr := validate.Verify(req)
	if errStr != "" {
		return nil, response.Error(400, errStr)
	}

	adminId := jwtx.GetAdminUserID(l.svcCtx.Config.Auth.AccessSecret, req.Token)
	log.Println("admin_id=", adminId)
	if adminId != 0 {
		// 查找是否在聊天用户里
		user, err := l.svcCtx.VisitorsModel.FindOneByAdminId(l.ctx, adminId)
		if err != nil {
			logx.Errorf("%d是否加入到用户里 %v", adminId, err.Error())
			return nil, response.Error(500, "系统错误")
		}
		now := time.Now().Unix()
		accessExpire := l.svcCtx.Config.Auth.AccessExpire
		accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, user.Id)
		if err != nil {
			logx.Errorf("%d生成token错误 %v", adminId, err.Error())
			return nil, response.Error(500, err.Error())
		}

		return &types.SysUserLoginResponse{
			AccessToken:  accessToken,
			AccessExpire: now + accessExpire,
		}, nil
	} else {
		return nil, response.Error(500, "系统错误")
	}
}
